<template>
  <div>
    <br>
    <el-tree
      :data="treeData"
      node-key="id"
      default-expand-all
      :expand-on-click-node="false">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button :disabled="node.level==3" type="primary" size="mini" @click="() => handleAddClick(node, data)" plain>添加子节点</el-button>
          <el-button :disabled="data.id==0" type="primary" size="mini" @click="() => handleEditClick(node, data)" plain>修改</el-button>
          <el-button :disabled="data.id==0" type="danger" size="mini" @click="() => handleRemoveClick(node, data)" plain>删除</el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog :title="!editing?'新建菜单':'编辑菜单'" :visible.sync="showEditDialog">
      <el-form ref="menuEditForm" :model="editMenu" :rules="editMenuRules">
      <el-form-item label="父节点" :label-width="formLabelWidth">
        {{ this.parentMenu==null?'根节点':this.parentMenu.name }}
      </el-form-item>
        <el-form-item label="菜单名" :label-width="formLabelWidth" prop="name">
          <div class="text-input">
            <el-input v-model="editMenu.name" auto-complete="off"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="模板路径" :label-width="formLabelWidth" prop="template">
          <div class="text-input">
            <el-input v-model="editMenu.template" auto-complete="off"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="链接路径" :label-width="formLabelWidth" prop="path">
          <div class="text-input">
            <el-input v-model="editMenu.path" auto-complete="off"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="图标" :label-width="formLabelWidth" prop="icon">
          <div class="text-input">
            <el-input v-model="editMenu.icon" auto-complete="off"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="级别" :label-width="formLabelWidth" prop="level">
          <div class="text-input">
            <el-input-number v-model="editMenu.level" :min="0" :max="1" label="级别"></el-input-number>
          </div>
        </el-form-item>
        <el-form-item label="排序" :label-width="formLabelWidth" prop="sort">
          <div class="text-input">
            <el-input-number v-model="editMenu.sort" :min="0" :max="1000" label="排序"></el-input-number>
          </div>
        </el-form-item>
        <el-form-item label="是否是叶子" :label-width="formLabelWidth" prop="leaf">
          <div class="text-input">
              <el-checkbox v-model="editMenu.leaf"></el-checkbox>
          </div>
        </el-form-item>
        <el-form-item label="是否隐藏" :label-width="formLabelWidth" prop="hidden">
          <div class="text-input">
              <el-checkbox v-model="editMenu.hidden"></el-checkbox>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showEditDialog = false">取 消</el-button>
        <el-button type="primary" @click="dialogConfirm()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      menuList: [],
      treeData: [],
      loading: false,
      total: 0,
      showEditDialog: false,
      editing: true,
      formLabelWidth: '100px',
      editMenu: {
        id: null,
        name: '',
        sort: 0,
        hidden: false,
        leaf: false,
        template: '',
        path: '',
        icon: '',
        level: 0,
        parent: {
          id: 0
        }
      },
      parentMenu: null,
      editMenuRules: {
        name: [
          { required: true, message: '请输入菜单名称', trigger: 'blur' },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
        ],
        path: [
          { required: true, message: '请输入链接地址', trigger: 'blur' },
          { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' }
        ],
        template: [
          { required: true, message: '请输入当前菜单对应的模板地址', trigger: 'blur' },
          { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    reloadMenuList: function () {
      this.loading = true
      var postData = {}
      this.$axios.post(this.$api.MENU_ALL.url, postData).then(response => {
        if (response.data.code === 0) {
          // 登录成功设置
          this.loading = false
          this.menuList = response.data.data.pageData.sort((x, y) => { return x.sort < y.sort })
          this.total = response.data.data.total
          console.log('response.data.data:', this.total, response.data.data)
          console.log('菜单:', this.total, this.menuList)
          this.genTree()
        }
      })
    },
    genTree: function () {
      var tree = [{ id: 0, label: '根节点', children: [] }]
      for (var i in this.menuList) {
        var menu = this.menuList[i]
        if (menu.parent === null) {
          var node = { id: menu.id, label: menu.name, children: [] }
          var children = this.menuList.filter((x) => {
            if (x.parent === null) {
              return false
            }
            return menu.id === x.parent.id
          })
          children.forEach((x) => {
            node.children.push({ id: x.id, label: x.name })
          })
          console.log('children', node.children)
          tree[0].children.push(node)
        }
      }
      this.treeData = tree
      console.log('tree', tree)
    },
    clearEditMenuForm: function () {
      this.editMenu.id = null
      this.editMenu.name = ''
      this.editMenu.sort = 0
      this.editMenu.hidden = false
      this.editMenu.leaf = false
      this.editMenu.template = ''
      this.editMenu.path = ''
      this.editMenu.level = 0
      this.editMenu.icon = ''
      if (this.$refs.menuEditForm) {
        this.$refs.menuEditForm.resetFields()
      }
    },
    handleAddClick: function (node, data) {
      this.editing = false
      this.clearEditMenuForm()
      this.showEditDialog = true
      this.editMenu.parent.id = data.id === 0 ? null : node.data.id
    },
    handleEditClick: function (node, data) {
      this.editing = true
      this.clearEditMenuForm()
      var menu = this.getMenuById(node.data.id)
      this.parentMenu = menu.parent === null ? null : this.getMenuById(menu.parent.id)
      this.editMenu.id = menu.id
      this.editMenu.name = menu.name
      this.editMenu.sort = menu.sort
      this.editMenu.hidden = menu.hidden
      this.editMenu.leaf = menu.leaf
      this.editMenu.template = menu.template
      this.editMenu.path = menu.path
      this.editMenu.level = menu.level
      this.editMenu.icon = menu.icon
      this.showEditDialog = true
      this.editMenu.parent.id = menu.parent === null ? null : menu.parent.id
    },
    handleRemoveClick: function (node, data) {
      var _this = this
      var menu = this.getMenuById(node.data.id)
      if (node.childNodes.length === 0) {
        this.$bus.$emit('showYesNo', '系统信息', '您要删除该菜单吗？', function () {
          var postData = { id: menu.id }
          this.$axios.post(this.$api.MENU_REMOVE.url, postData).then(response => {
            console.log('respone', response)
            if (response.data.code === 0) {
              this.$message({
                message: '操作成功!',
                type: 'success'
              })
              _this.reloadMenuList()
            }
          })
        })
      } else {
        this.$message.error('该节点包含其他节点，请删除子节点，再删除该节点!')
      }
    },
    getMenuById: function (id) {
      return this.menuList.find(x => x.id === id)
    },
    dialogConfirm: function () {
      this.$refs['menuEditForm'].validate((valid) => {
        if (valid) {
          var url = this.editing ? this.$api.MENU_UPDATE.url : this.$api.MENU_ADD.url
          var postData = JSON.parse(JSON.stringify(this.editMenu))
          console.log(url, postData)
          this.$axios.post(url, postData).then(response => {
            if (response.data.code === 0) {
              // 登录成功设置
              this.loading = false
              this.$message({
                message: '操作成功!',
                type: 'success'
              })
              this.showEditDialog = false
              this.reloadMenuList()
            }
          }).catch((err) => {
            this.logining = false
            this.$message.error(err.message)
          })
        }
      })
    }
  },
  created: function () {
    this.reloadMenuList()
  }
}
</script>
<style>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
  .el-tree-node__content {
    height: 36px !important;
  }
  .text-input{
  width:240px;
}
</style>
